Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Trait System to GDScript #97657

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

SeremTitus
Copy link

@SeremTitus SeremTitus commented Sep 30, 2024


GDScript Trait System

Based on the discussion opened in:

The GDScript trait system allows traits to be declared in separate .gdt files or within a trait SomeTrait block.

Traits facilitate efficient code reuse by enabling classes to share and implement common behaviors, reducing duplication and promoting maintainable design.

Syntax Breakdown

Declaring Traits

  • Traits can be defined globally or within classes.

  • In a .gdt file, declare a global trait using trait_name GlobalTrait at the top. trait used for inner traits.

  • Traits can contain all class members: enums, signals, variables, constants, functions and inner classes.

    Example:

    # SomeTrait.gdt
    trait_name SomeTrait
    
    # Trait types used for typing containers.
    var player: TraitPlayable
    var scene_props: Array[TraitMoveable]
    var collected: Dictionary[String, TraitCollectable]
    
    func _ready():
        pass  # Method with implementation, but can be overridden.
    
    # Method to be implemented by the class using the trait.
    # The return type must be `void`.
    func foo() -> void # Bodyless need to be implemented in class using trait.
    
    # The return type can be overridden, but it's not required to specify one.
    func some_method() # Bodyless need to be implemented in class using trait.
    
    # The return type can be overridden but must be a class that inherits from `Node`.
    func some_other_method() -> Node  # Bodyless need to be implemented in class using trait.
    

Using Traits in Classes

  • Use the uses keyword after the extends block, followed by the path or global name of the trait.

  • Traits can include other traits but do not need to implement their unimplemented functions. The implementation burden falls on the class using the trait.

    Example:

    # SomeClass.gd
    extends Node
    
    uses Shapes, Topology  # Global traits
    uses "res://someOtherTrait.gdt"  # File-based trait
    
    func _ready():
        var my_animals : Array = []
        my_animals.append(FluffyCow.new())
        my_animals.append(FluffyBull.new())
        my_animals.append(Bird.new())
        var count = 1
        for animal in my_animals:
            print("Animal ", count)
            if animal is Shearable:
                animal.shear()
            if animal is Milkable:
                animal.milk()
            count += 1
    
    trait Shearable:
        func shear() -> void:
            print("Shearable ok")
    
    trait Milkable:
        func milk() -> void:
            print("Milkable ok")
    
    class FluffyCow:
        uses Shearable, Milkable
    
    class FluffyBull:
        uses Shearable
    
    class Bird:
        pass

Creating Trait files.

  • In Editor go to FileSystem, left click and select "New Script ...". In the pop up select GDTrait as the preferred Language.
  • Alternatively in script creation pop up instead of selecting GDTrait from 'Language' dropdown menu change 'path' extention to '.gdt' and language will automatic change to GDTrait
    image

How Traits Are Handled

Cases

When a class uses a trait, its handled as follows:

1. Trait and Class Inheritance Compatibility:

The trait's inheritance must be a parent of the class's inheritance (compatible), but not the other way around, else an error occurs. Also note traits are pass down by inheritance, If a class is for instance "SomeTrait" also it here classes will be so.

Example:
    # TraitA.gdt
    trait_name TraitA extends Node

    # ClassA.gd
    extends Control
    uses TraitA  # Allowed since Control inherits from Node

2. Used Traits Cohesion:

When a class uses various traits, some traits' members might shadow other traits members ,hence, an error should occur when on the trait relative on the order it is declared.

3. Enums, Constants, Variables, Signals, Functions and Inner Classes:

These are copied over, or an error occurs if they are shadowed.

4. Extending Named Enums:

Named enums can be redeclared in class and have new enum values.
Note that unnamed enum are just copied over if not shadowing.

5. Overriding Variables:

This is allowed if the type is compatible and the value is changed.
Or only the type further specified. Export, Onready, Static state of trait variables are maintained. Setter and getter is maintained else overridden (setters parameters same and the ).

6. Overriding Signal:

This is allowed if parameter count are maintained and the parameter types is compatible by further specified from parent class type.

Example:

    # TraitA.gdt
    trait_name TraitA
    signal someSignal(out: Node)

    # ClassA.gd
    uses TraitA
    signal someSignal(out: Node2D) # Overridden signal

7. Overriding Functions:

Allowed if parameter count are maintained, return types and parameter types are compatible, but the function body can be changed. Static and rpc state of trait functions are maintained.

8. Unimplemented (Bodyless) Functions:

The class must provide an implementation. If a bodyless function remains unimplemented, an error occurs. Static and rpc state of trait functions are maintained.

9. Extending Inner Classes:

Inner classes defined in used trait can be redeclared in class and have new members provide not shadow members declared inner class declared in trait. Allow Member overrides for variables, Signals and function while extending Enum and its' Inner Classes.

Example:

    # Shapes.gdt
    trait_name Shapes
    class triangle: # Declared
        var edges:int = 3
        var face:int = 1
        func print_faces():
            print(face)


    # Draw.gd
    uses Shapes
    class triangle: # Redeclared
        var verticies:int = 3 # Add a new member
        var face:int =  2 # Overriding Variable
        func print_faces(): # Overriding Function
            print(face-1)

Special Trait Features

10. Trait can use other Traits:

A trait is allows to use another trait except it does not alter members of the trait it is using by overriding or extending.
However, cyclic use of traits (TraitA uses TraitB and TraitB uses TraitA) is not permitted and will result in error.

11. Tool Trait:

if one trait containing the @tool keyword is used it converts classes (except inner classes) and traits using it into tool scripts.

12. File-Level Documentation:

Member documentation is copied over from trait else overridden.


System Implementation Progress

  • Implement and verify How Traits Are Handled
  • Debugger Integration
  • Trait typed Assignable (variable, array, dictionary)
  • Trait type as method & signal parameters' type
  • Trait type as method return type
  • Trait type casting (as)
  • Class is Trait type compatibility check (is)
  • Make .gdt files unattachable to objects/nodes
  • Hot reloadable Classes using traits when trait Changes (for Editor and script documentation)
  • Making Traits not directly accessible member/calls/instancing
  • Write Tests
  • Write Documentation (user manual)

Bugsquad edit:

@DaloLorn
Copy link

Is there a specific reason you specified a void return type for foo()? Do abstract methods always need a strictly defined return type?

If not, might I recommend a different return type for clarity?

@AdriaandeJongh
Copy link
Contributor

AdriaandeJongh commented Oct 1, 2024

(Edited because I missed a part in the OP description)

Fantastic start on this feature. Thank you!

One comment: please use implements over uses, as per the original proposal.

@DaloLorn
Copy link

DaloLorn commented Oct 1, 2024

I'm not sure your reasoning lines up with your conclusion there, but I can't say I have much of a preference, what with it being a strictly cosmetic affair.

@btarg
Copy link

btarg commented Oct 1, 2024

This system seems very similar to the abstract keyword, which has already been suggested.. what makes this approach better than abstract classes?
I already use a lot of base classes with empty functions that are then overridden in my game currently. Will this improve the workflow comparatively?

@DaloLorn
Copy link

DaloLorn commented Oct 1, 2024

Abstract classes are still beholden to the class hierarchy: No class can inherit from two classes at a time.

There is some value in having both of these, I suppose, but traits are far more powerful.

@dalexeev
Copy link
Member

dalexeev commented Oct 1, 2024

This system seems very similar to the abstract keyword, which has already been suggested.. what makes this approach better than abstract classes?

See:

Also, as DaloLorn said, these are independent features that can coexist together. Traits offer capabilities that classic inheritance cannot provide.

@rrenna
Copy link

rrenna commented Oct 1, 2024

This looks great, will traits be able to constrain typed collections (ie. Array[Punchable], Dictionary[String, Kickable]) ?

@Dynamic-Pistol
Copy link

Amazing that somebody cared to make this,but since the original proposal is shut down,here is some feedback

  1. use impl instead of uses,this makes more sense and also is short too
  2. don't have a seperate file extension for traits,have .gd files be able to support different object types
  3. no trait_name, name it instead type_name
  4. traits should only have functions (abstract and virtual),no other stuff

@RadiantUwU
Copy link
Contributor

RadiantUwU commented Oct 2, 2024

  1. traits should only have functions (abstract and virtual),no other stuff

Considering work has already been made for signals, we should get to keep them too. (unless massive performance issues appear)

@Mickeon
Copy link
Contributor

Mickeon commented Oct 2, 2024

I am a bit concerned on the performance of this in general, but that would be something that can be solved over time. I am really, really ecstatic about this.

I agree. There's no reason to exclude signals from traits if the work has been done.

@SeremTitus SeremTitus force-pushed the GDTraits branch 2 times, most recently from 36d7605 to 4088f53 Compare October 3, 2024 14:57
Copy link
Contributor

@RadiantUwU RadiantUwU left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just some nitpicks, mostly you should rename uses with impl everywhere.

modules/gdscript/gdscript.cpp Show resolved Hide resolved
modules/gdscript/gdscript_analyzer.cpp Outdated Show resolved Hide resolved
modules/gdscript/gdscript_analyzer.cpp Show resolved Hide resolved
modules/gdscript/gdscript_analyzer.cpp Show resolved Hide resolved
modules/gdscript/gdscript_analyzer.h Show resolved Hide resolved
modules/gdscript/gdscript_parser.h Show resolved Hide resolved
modules/gdscript/gdscript_parser.h Show resolved Hide resolved
modules/gdscript/gdscript_parser.h Show resolved Hide resolved
modules/gdscript/gdscript_tokenizer.cpp Show resolved Hide resolved
modules/gdscript/gdscript_tokenizer.h Show resolved Hide resolved
@AdriaandeJongh
Copy link
Contributor

AdriaandeJongh commented Oct 4, 2024

As various others have suggested to use impl instead of implements, I wanted to make a case against impl. Take this example:

class_name SomeClass
extends BaseClass
impl TraitA
  • impl is inconsistently abbreviated next to the written-out extends and class_name keywords that will almost always be just above or below it.
  • for non-native English speakers, impl is harder to understand at first glance, and un-google-able for translation.
  • If contributors want Godot to be beginner friendly, writing out implements is the more friendly option here, because it requires less knowledge of the programming language and associated jargon.
  • as rightfully mentioned on mastodon in response to me yapping about engine UX, impl could imply "implies", "impels", "implant", "implode".

The 6 characters impl saves over implements is not worth the confusion and inconsistency. Instead, perhaps you would agree with me that this is much more readable and consistent:

class_name SomeClass
extends BaseClass
implements TraitA

@Dynamic-Pistol
Copy link

impl is inconsistently abbreviated next to the written-out extends and class_name keywords that will almost always be just above or below it.

what would you abbreviate extends and class_name to? only answers i can think of is for class_name, which could be changed to use the script name, and extends could just be extend

for non-native English speakers, impl is harder to understand at first glance, and un-google-able for translation.

Pretty sure non-native speakers are able to understand abbreviations, by your logic int and bool should be Integer and Boolean, this doesn't include all the abbreviated types that exist already

If contributors want Godot to be beginner friendly, writing out implements is the more friendly option here, because it requires less knowledge of the programming language and associated jargon.

traits aren't exactly beginner stuff, when someone starts with a language they learn they might learn traits ,but for gamedev you don't learn certain stuff until you get the basics/become a casual programmer , when i was a unity developer, i didn't learn about interfaces (which are extremely similar to traits) until i had advanced enough and realised i need some other solution to inheritance

as rightfully mentioned on mastodon in response to me yapping about engine UX, impl could imply "implies", "impels", "implant", "implode".

this makes no sense? let's take a look at some example code:

class_name Door
extends AnimatableBody3D
impl Interactable

what would "implies" mean in a progammer context?, "impels" isn't even abbreviated correctly, "implant"? seriously?, "implode" would be a function for gameplay

The 6 characters impl saves over implements is not worth the confusion and inconsistency. Instead, perhaps you would agree with me that this is much more readable and consistent

previous points still matter, also rust uses the impl keyword, and i am pretty sure it popularized the concept of traits and yet still 0 complains from it

@OscarCookeAbbott
Copy link

Is using a separate file extension necessary? And if not, would it be better to stick to .gd? From a UX perspective it seems a lot simpler and easier not to.

@eon-s
Copy link
Contributor

eon-s commented Oct 4, 2024

Is using a separate file extension necessary? And if not, would it be better to stick to .gd? From a UX perspective it seems a lot simpler and easier not to.

Extensions can be useful for quick search, filter, etc., without the need to check the content of the file nor adding extra prefix/suffix to file names (so it's better in UX terms), also can help other tools like the filesystem to implement custom icons.

@DaloLorn
Copy link

DaloLorn commented Oct 4, 2024

Put me down as another vote in favor of "implements", for what it's worth. I'm indifferent on "implements" versus "uses", but I'm not nearly so indifferent on "impl" versus "implements": The majority of Adriaan's concerns have not been addressed to my satisfaction.

@JJulioTLG
Copy link

JJulioTLG commented Oct 4, 2024

As various others have suggested to use impl instead of implements, I wanted to make a case against impl. Take this example:

class_name SomeClass
extends BaseClass
impl TraitA
  • impl is inconsistently abbreviated next to the written-out extends and class_name keywords that will almost always be just above or below it.
  • for non-native English speakers, impl is harder to understand at first glance, and un-google-able for translation.
  • If contributors want Godot to be beginner friendly, writing out implements is the more friendly option here, because it requires less knowledge of the programming language and associated jargon.
  • as rightfully mentioned on mastodon in response to me yapping about engine UX, impl could imply "implies", "impels", "implant", "implode".

The 6 characters impl saves over implements is not worth the confusion and inconsistency. Instead, perhaps you would agree with me that this is much more readable and consistent:

class_name SomeClass
extends BaseClass
implements TraitA

I think uses is fine.

@antimundo
Copy link

I agree on "impl" been a very confusing keyword.

@RadiantUwU
Copy link
Contributor

RadiantUwU commented Oct 7, 2024

To resolve the class reference error: Compile godot, then run ./bin/godot<TAB> --doctool, then push the result.

@SeremTitus SeremTitus force-pushed the GDTraits branch 2 times, most recently from f27a5d9 to 8d2b91c Compare October 9, 2024 17:35
@SeremTitus
Copy link
Author

While working on the documentation, I found behavior with static variables in traits that seems like it might not make sense?

Nice catch, that was a bug. It is now fix and have write a test for it.
Here example how it should work

trait SomeTrait:
	static var some_static_var = 0
	static var other_static_var = 0
	static var third_static_var = 0
	static func some_static_func():
		print("some static func")
	static func other_static_func():
		print("other static func")
	static func third_static_func():
		print("third static func")

class SomeClass:
	uses SomeTrait
	# Overridden static variable
	var other_static_var = 1 # using 'static' keyword is optional
	static var third_static_var = 1
	# Overridden static function
	func other_static_func(): # using 'static' keyword is optional
		print("overridden other static func")
	static func third_static_func():
		print("overridden third static func")

func _ready():
	print(SomeClass.some_static_var)
	print(SomeClass.other_static_var)
	print(SomeClass.third_static_var)
	SomeClass.some_static_func()
	SomeClass.other_static_func()
	SomeClass.third_static_func()
	print("ok")

If static function/variable is declared in a trait, when redeclared/overridden in class should using 'static' keyword is optional ? (currently it is)

because some_var is static to the trait itself, so you would have to do

print(SomeTrait.some_var)

This is not correct traits are not object and should not be instanced or called, I will look for way to better communicate this to prevent misuse.

@Meorge
Copy link
Contributor

Meorge commented Dec 11, 2024

If static function/variable is declared in a trait, when redeclared/overridden in class should using 'static' keyword is optional ? (currently it is)

Personally, I strongly feel that the static keyword should not be optional. If the user wants to redefine its value for a class that uses a trait, then I think one of these should work:

class MyClass:
    uses MyTrait
    static var some_static_var  = 2  # inherited from MyTrait
    # OR
    some_static_var = 2  # also inherited from MyTrait

The static var count = ... makes it clear to whoever's reading this class file that count is a static variable, whereas if it was simply var count = ... they would naturally assume it's an instance variable and be confused when they're not allowed to do instance.count.

Simply having count = ... works with the idea that we've already declared the variable itself in the trait, and now we're just modifying the value here, like how var local_value = ... initializes the variable and local_value = ... changes the value. I could see others being opposed to this syntax being up at the class member definition level, though, and can understand their reasoning, so overall I think just requiring the static keyword makes the most sense.

@Meorge
Copy link
Contributor

Meorge commented Dec 12, 2024

I pulled the recent changes to verify the static variable behavior, and while it looks like it's closer to what is expected (at least to me), I think I may have found an inconsistency with it. I used this code:

extends Node2D

trait HasStatic:
    static var static_var = 3

class UsingClass:
    uses HasStatic
    
class DifferentUsingClass:
    uses HasStatic

func _ready():
    UsingClass.static_var = 2
    print("HasStatic's value: ", HasStatic.static_var)
    print("UsingClass's value: ", UsingClass.static_var)
    print("DifferentUsingClass's value: ", DifferentUsingClass.static_var)

This prints out:

HasStatic's value: <null>
UsingClass's value: 2
DifferentUsingClass's value: <null>

I would expect it to print out:

HasStatic's value: 3
UsingClass's value: 2
DifferentUsingClass's value: 3

Does this sound like unexpected behavior, or am I missing something with how static variables are expected to work in traits?

@SeremTitus SeremTitus force-pushed the GDTraits branch 2 times, most recently from e010b36 to 4b9bac0 Compare December 12, 2024 20:18
@SeremTitus
Copy link
Author

SeremTitus commented Dec 12, 2024

I pulled the recent changes to verify the static variable behavior, and while it looks like it's closer to what is expected (at least to me), I think I may have found an inconsistency with it.

Fixed and now has a test.


 print("HasStatic's value: ", HasStatic.static_var)

This is illegal, now you get an error, traits should be considered as templates and can not be objects ,hence, not directly access to its member, calling or instancing.


class SomeClass:
	uses SomeTrait
	# Overridden static variable
	var other_static_var = 1 # using 'static' keyword is optional
	static var third_static_var = 1

I decided to go with this remaining optional, however, you get a warning. same applies on overriding variables that use @onready

@SeremTitus SeremTitus marked this pull request as ready for review December 12, 2024 20:28
@SeremTitus SeremTitus requested review from a team as code owners December 12, 2024 20:28
@KoBeWi
Copy link
Member

KoBeWi commented Dec 13, 2024

This simple code fails:

trait TestTrait extends Node:
	pass

func test_func(node: Node):
	if node is TestTrait:
		pass
Expression is of type "Node" so it can't be of type "TestTrait".

This works:

func test_func(node: Node):
	var traiter := node as TestTrait
	if traiter:
		pass

@Meorge
Copy link
Contributor

Meorge commented Dec 13, 2024

I can double-check on my end, but I thought the syntax for inner traits would be:

trait TestTrait:
    extends Node

?

Edit: Regardless of which syntax is correct (or if both are), my variation gets the same error:

trait TestTrait2:
    extends Node

func test_func(node: Node):
    if node is TestTrait2:
        pass
Expression is of type "Node" so it can't be of type "TestTrait2".

@KoBeWi
Copy link
Member

KoBeWi commented Dec 13, 2024

Some editor bugs:

  • Overriden methods from trait don't show inherited icon.
    image
    (attack() is from a trait)
    You also can't Ctrl+Click it to go to base implementation.

  • Saving a trait used in a built-in script, makes this script "unsaved":

godot.windows.editor.dev.x86_64_SVznbLcOmV.mp4

EDIT:
Cyclic dependencies have problems. I have a global class with enum, and it refers to a trait and the trait uses the enum as a type for one of variables.

In a script that tries to use this trait I get this error:

Parser bug (please report): Could not find external parser for class "Player". (Trying to resolve datatype of class member)

In another project I had error that variables were not found when trying to refer to variables from trait, not sure how to reproduce it.

The bugged scripts:
Traits.zip
The script with error:

extends Node
uses PlayerWeapon

func _ready() -> void:
	attack_type = 5 # If the script manages to parse, this will result in runtime error.

EDIT2:
I tried to workaround the above by moving the enum to trait, but trait enumes can't be used without class. That's rather unexpected tbh.

@KoBeWi
Copy link
Member

KoBeWi commented Dec 13, 2024

Edit: Regardless of which syntax is correct (or if both are), my variation gets the same error:

In your variation the trait extends RefCounted (default base class), so the error is correct.

EDIT:
Or at least I assumed that based on how classes work currently.
Maybe it's worth it to make the default Object? Classes using traits need their own extend anyway, so this would make traits more universal.

@@ -288,12 +317,25 @@ String ScriptCreateDialog::_validate_path(const String &p_path, bool p_file_must
if (!found) {
return TTR("Invalid extension.");
}
if (!match) {
if (!match && _extention_update_selected_language(p.get_extension()) != OK) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (!match && _extention_update_selected_language(p.get_extension()) != OK) {
if (!match && _extension_update_selected_language(p.get_extension()) != OK) {

return language->validate_path(p);
}

Error ScriptCreateDialog::_extention_update_selected_language(const String &p_extention) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Error ScriptCreateDialog::_extention_update_selected_language(const String &p_extention) {
Error ScriptCreateDialog::_extension_update_selected_language(const String &p_extension) {

Error ScriptCreateDialog::_extention_update_selected_language(const String &p_extention) {
for (int i = 0; i < language_list.size(); i++) {
ScriptLanguage *lang = language_list[i];
if (p_extention == lang->get_extension()) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (p_extention == lang->get_extension()) {
if (p_extension == lang->get_extension()) {

@@ -100,6 +102,7 @@ class ScriptCreateDialog : public ConfirmationDialog {
void _use_template_pressed();
bool _validate_parent(const String &p_string);
String _validate_path(const String &p_path, bool p_file_must_exist);
Error _extention_update_selected_language(const String &p_extention);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Error _extention_update_selected_language(const String &p_extention);
Error _extension_update_selected_language(const String &p_extension);

</brief_description>
<description>
See [GDScript] or [@GDScript] instead.
Helper Script to store Traits for GDScript, its not attachable to objects [method Object.set_script].Saved with the [code].gdt[/code] extension, for GDScript programming language external Traits.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Helper Script to store Traits for GDScript, its not attachable to objects [method Object.set_script].Saved with the [code].gdt[/code] extension, for GDScript programming language external Traits.
Script resource to store traits for GDScript created with the [code].gdt[/code] file extension, allows defining and requiring common methods across multiple classes, along with anything that you would see inside of a GDScript class (signals, classes, etc.).

<description>
See [GDScript] or [@GDScript] instead.
Helper Script to store Traits for GDScript, its not attachable to objects [method Object.set_script].Saved with the [code].gdt[/code] extension, for GDScript programming language external Traits.
Note that it can not be instanced.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Note that it can not be instanced.
[b]Note:[/b] Unlike [GDScript], this resource cannot create instances (see [method GDScript.new]) due to its abstract nature.

<?xml version="1.0" encoding="UTF-8" ?>
<class name="GDTrait" inherits="GDScript" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd">
<brief_description>
A script implemented in the GDScript programming language.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
A script implemented in the GDScript programming language.
Script resource to store traits for GDScript.

@Dynamic-Pistol
Copy link

Dynamic-Pistol commented Dec 13, 2024

since the og proposal is locked, i am forced to state my opinion here, i believe traits shouldn't have variables, i can go overkill and say signals don't deserve to be in traits, but i feel (not know) there may be cases where signals are needed, but variables? pretty sure only C++ does this and C++ is known for tons of bad stuff, if variables are desperately needed, once can use a function getter and setter and otherwise should be in classes, for static stuff, i am not really sure how static stuff would even work, static stuff is related to the type, and traits are types, and we would need reflection/metaprogramming, to better explain

trait Interactable:
    pass

func f():
    if i is Interactable:
        i.interact()
    if typeof(i).traits.has(Interactable):
       typeof(i).static_interact()

get it now? if a type requires a static method, chances are you would put it in the class

quick edit: the prev code is a mock code of what is gdscript needs to have to use static functions correctly and is meant to showcase how useless and troublesome it will be

@tehKaiN
Copy link

tehKaiN commented Dec 13, 2024

signals are helpful in interfaces/traits since you can do something like:

trait_name Destroyable:

signal destroyed(self: Destroyable)

@eon-s
Copy link
Contributor

eon-s commented Dec 13, 2024

@Dynamic-Pistol you can create a discussion to talk about this

I don't want to extend the off topic but I want to add that the implications of variables in traits are huge and can add a lot of flexibility, just think on how these can be used in resources and other data types, to extend and to patch them

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add a Trait system for GDScript